import { createRouter, createWebHashHistory } from "vue-router";
import {
  $go2,
  dynamicRouter,
} from "../utils/routerUtil";
import { close, start } from "../utils/nprogress";
import { getUserInfo } from "../api/api";
import { getMenus } from "@/utils/menuUtils";
import store from "@/store/store";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "登录",
      component: () => import("../pages/Login.vue"),
    },
    {
      path: "/layout",
      name: "主页布局",
      component: () => import("../component/Layout/Layout.vue"),
      redirect: "/layout/home",
      children: [
        {
          path: "home",
          name: "首页",
          component: () => import("../pages/Home.vue"),
          meta: {
            btn: [],
          },
        },
      ],
    },
  ],
});

/**
 * 导航守卫
 */
router.beforeEach((to) => {
  start();
  const token = localStorage.getItem("token");
  if (token) {
    if (router.getRoutes().length === 3) {
      try {
        getUserInfo()
          .then(({ result }: any) => {
            dynamicRouter(result);  
            const menuArray = getMenus(result);
            store.commit("ADD_MENU",menuArray);
            router.replace(router.currentRoute.value.fullPath);
          })
          .catch((err: any) => {
            console.log(err);
          });
      } catch (error) {
        // 报错跳转登录页
        $go2("/");
      }
    }
    // 添加路由菜单
    const path:string=to.path.split("/")[2];
    // 0.1秒之后添加标签数组
    setTimeout(()=>{
            const routeName=store.state.routeMap.get(path);
            if (to.path != "/") {
            store.commit("ADD_PAGE", {
            name: to.name === undefined ? routeName : to.name,
            path: to.path,
          });
        }
    },200)
  }
});

router.afterEach(() => {
  close();
});

export default router;
